package cn.kshost.zqyg.order.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.kshost.zqyg.client.cart.CartFeign;
import cn.kshost.zqyg.client.product.ProductFeign;
import cn.kshost.zqyg.client.user.UserAddressFeign;
import cn.kshost.zqyg.exception.ZhongQiaoException;
import cn.kshost.zqyg.model.dto.h5.OrderInfoDto;
import cn.kshost.zqyg.model.entity.h5.CartInfo;
import cn.kshost.zqyg.model.entity.order.OrderInfo;
import cn.kshost.zqyg.model.entity.order.OrderItem;
import cn.kshost.zqyg.model.entity.order.OrderLog;
import cn.kshost.zqyg.model.entity.product.ProductSku;
import cn.kshost.zqyg.model.entity.user.UserAddress;
import cn.kshost.zqyg.model.vo.common.ResultCodeEnum;
import cn.kshost.zqyg.model.vo.h5.TradeVo;
import cn.kshost.zqyg.order.mapper.OrderInfoMapper;
import cn.kshost.zqyg.order.mapper.OrderItemMapper;
import cn.kshost.zqyg.order.mapper.OrderLogMapper;
import cn.kshost.zqyg.order.service.OrderService;
import cn.kshost.zqyg.utils.AuthContextUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class OrderServiceImpl implements OrderService {

    @Autowired
    private CartFeign cartFeign;
    @Autowired
    private ProductFeign productFeign;
    @Autowired
    private UserAddressFeign userAddressFeign;
    @Autowired
    private OrderInfoMapper orderInfoMapper;
    @Autowired
    private OrderItemMapper orderItemMapper;
    @Autowired
    private OrderLogMapper orderLogMapper;
    @Override
    public TradeVo trade() {
        List<CartInfo> cartInfoList = cartFeign.getAllChecked().getData();
        ArrayList<OrderItem> orderItems = new ArrayList<>();
        cartInfoList.stream().forEach(cartInfo -> {
            OrderItem orderItem = new OrderItem();
            orderItem.setSkuId(cartInfo.getSkuId());
            orderItem.setSkuName(cartInfo.getSkuName());
            orderItem.setSkuNum(cartInfo.getSkuNum());
            orderItem.setSkuPrice(cartInfo.getCartPrice());
            orderItem.setThumbImg(cartInfo.getImgUrl());
            orderItems.add(orderItem);
        });
        BigDecimal totalAmount = BigDecimal.ZERO;
        for (OrderItem orderItem : orderItems) {
            totalAmount=  totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItems);
        return tradeVo;
    }
    @Override
    @Transactional
    public Long submitOrder(OrderInfoDto orderInfoDto) {
        //查询商品库存是否存在
        List<OrderItem> orderItemList = orderInfoDto.getOrderItemList();
        if (CollectionUtil.isEmpty(orderItemList)) {
            throw  new ZhongQiaoException(ResultCodeEnum.DATA_ERROR);}
        for (OrderItem orderItem : orderItemList) {
            Long skuId = orderItem.getSkuId();
            ProductSku productSku = productFeign.getBySkuId(skuId).getData();
            if (productSku == null) {
                throw  new ZhongQiaoException(ResultCodeEnum.DATA_ERROR);
            }
            //库存校验
            if (productSku.getStockNum() < orderItem.getSkuNum()) {
                throw  new ZhongQiaoException(ResultCodeEnum.STOCK_LESS);
            }}
        //获取用户地址
        UserAddress userAddress = userAddressFeign.findUserAddressById(orderInfoDto.getUserAddressId()).getData();
        Long userId = userAddress.getUserId();
        //检验地址是否是否属于该用户
        if (userId != AuthContextUtil.getUserInfoValue().getId()) {
         throw  new  ZhongQiaoException(ResultCodeEnum.DATA_ERROR);}
        //插入订单信息
        OrderInfo orderInfo = new OrderInfo();
        orderInfo.setReceiverName(userAddress.getName());
        orderInfo.setReceiverPhone(userAddress.getPhone());
        orderInfo.setReceiverTagName(userAddress.getTagName());
        orderInfo.setReceiverProvince(userAddress.getProvinceCode());
        orderInfo.setReceiverCity(userAddress.getCityCode());
        orderInfo.setReceiverDistrict(userAddress.getDistrictCode());
        orderInfo.setReceiverAddress(userAddress.getFullAddress());
        //订单金额
        BigDecimal totalAmount = new BigDecimal(0);
        for (OrderItem orderItem : orderItemList) {
            totalAmount = totalAmount.add(orderItem.getSkuPrice().multiply(new BigDecimal(orderItem.getSkuNum())));
        }
        orderInfo.setTotalAmount(totalAmount);//实际总金额
        orderInfo.setCouponAmount(new BigDecimal(0));//优惠券
        orderInfo.setOriginalTotalAmount(totalAmount);//原始总金额
        orderInfo.setFeightFee(orderInfoDto.getFeightFee());//运费
        orderInfo.setPayType(2);//支付方式【1->微信 2->支付宝】
        orderInfo.setOrderStatus(0);//订单状态【0->待付款；1->待发货；2->已发货；3->待用户收货，已完成；-1->已取消】
        orderInfo.setRemark(orderInfoDto.getRemark());
        //订单编号
        orderInfo.setOrderNo(String.valueOf(System.currentTimeMillis()));
        //用户id
        orderInfo.setUserId(userId);
        //用户昵称
        orderInfo.setNickName(AuthContextUtil.getUserInfoValue().getNickName());
        orderInfoMapper.insertOrderInfo(orderInfo);
        //插入订单商品信息
        orderItemList.stream().forEach(orderItem -> {
            orderItem.setOrderId(orderInfo.getId());
        });
        orderItemMapper.insertOrderItemList(orderItemList);
        //插入订单日志
        OrderLog orderLog = new OrderLog();
        orderLog.setProcessStatus(0);
        orderLog.setNote("提交订单");
        orderLog.setOrderId(orderInfo.getId());
        orderLogMapper.insertOrderLog(orderLog);
        //清空购物车
        cartFeign.clearCart();
        return orderInfo.getId();
    }

    @Override
    public OrderInfo getOrderInfo(Long orderId) {
        OrderInfo orderInfo =   orderInfoMapper.selectOrderInfoById(orderId);
        return orderInfo;
    }

    @Override
    public TradeVo getBuyOrderInfo(Long skuId) {
        // 查询商品
        ProductSku productSku = productFeign.getBySkuId(skuId).getData();
        if (productSku == null ) {
            throw   new ZhongQiaoException(ResultCodeEnum.DATA_ERROR);
        }
        if (productSku.getStockNum() < 1) {
            throw  new ZhongQiaoException(ResultCodeEnum.STOCK_LESS);
        }
        List<OrderItem> orderItemList = new ArrayList<>();
        OrderItem orderItem = new OrderItem();
        orderItem.setSkuId(skuId);
        orderItem.setSkuName(productSku.getSkuName());
        orderItem.setSkuNum(1);
        orderItem.setSkuPrice(productSku.getSalePrice());
        orderItem.setThumbImg(productSku.getThumbImg());
        orderItemList.add(orderItem);
        // 计算总金额
        BigDecimal totalAmount = productSku.getSalePrice();
        TradeVo tradeVo = new TradeVo();
        tradeVo.setTotalAmount(totalAmount);
        tradeVo.setOrderItemList(orderItemList);
        return tradeVo;
    }

    @Override
    public PageInfo<OrderInfo> getOrderInfoPage(Integer page, Integer limit, Integer orderStatus) {
        PageHelper.startPage(page, limit);
        Long id = AuthContextUtil.getUserInfoValue().getId();
        List<OrderInfo> orderInfoList =  orderInfoMapper.selectOrderInfoListByorderStatus(id,orderStatus);
       PageInfo<OrderInfo> pageInfo = new PageInfo<>(orderInfoList);

       //根据订单id获取订单商品列表
        orderInfoList.stream().forEach(orderInfo -> {
            Long orderInfoId = orderInfo.getId();
           List<OrderItem> orderItemList =  orderItemMapper.selectOrderItemListByOrderInfoId(orderInfoId);
           orderInfo.setOrderItemList(orderItemList);
        });
       return pageInfo;
    }

    @Override
    public OrderInfo getOrderInfoByOrderNo(Long orderNo) {
       OrderInfo orderInfo =  orderInfoMapper.selectOrderInfoByOrderNo(orderNo);
        //根据 订单id查询订单详情
        List<OrderItem> orderItemList = orderItemMapper.selectOrderItemListByOrderInfoId(orderInfo.getId());
        orderInfo.setOrderItemList(orderItemList);
        return orderInfo;
    }

    @Override
    public void updateOrderStatus(String orderNo, int payType) {
        // 更新订单状态
        OrderInfo orderInfo = orderInfoMapper.selectOrderInfoByOrderNo(Long.valueOf(orderNo));
        orderInfo.setOrderStatus(1);
        orderInfo.setPayType(payType);
        orderInfo.setPaymentTime(new Date());
        orderInfoMapper.updateById(orderInfo);

        // 记录日志
        OrderLog orderLog = new OrderLog();
        orderLog.setOrderId(orderInfo.getId());
        orderLog.setProcessStatus(1);
        orderLog.setNote("支付宝支付成功");
        orderLogMapper.insertOrderLog(orderLog);
    }


}
